﻿using System;
using System.Runtime.Remoting.Messaging;

namespace CallTraceSample
{
    class CallTraceSink : IMessageSink
    {
        private IMessageSink nextSink;

        public CallTraceSink(IMessageSink next)
        {
            nextSink = next;
        }

        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            throw new NotImplementedException();
        }

        public IMessageSink NextSink
        {
            get { return nextSink; }
        }

        public IMessage SyncProcessMessage(IMessage msg)
        {
            Preprocess(msg);
            IMessage retMsg = nextSink.SyncProcessMessage(msg);
            Postprocess(msg, retMsg);
            return retMsg;
        }

        private void Preprocess(IMessage msg)
        {
            IMethodCallMessage call = msg as IMethodCallMessage;

            if (call == null) return;

            Console.WriteLine("Preprocess:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
        }

        private void Postprocess(IMessage msg, IMessage retMsg)
        {
            IMethodCallMessage call = msg as IMethodCallMessage;

            if (call == null) return;

            Console.WriteLine("Postprocess:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
        }
    }
}
